<template>
  <div class="detail-resource-wrap">
    <template v-if="!permissionDenied">
      <div v-if="!showMobilePage || (historyResourceList && historyResourceList.length)" class="detail-top-container">
        <div v-if="!showMobilePage" class="title">资源详情</div>
        <div v-if="historyResourceList && historyResourceList.length" :class="{'is-mobile':showMobilePage}" class="history-resource-list">
          <div class="name">资源版本</div>
          <el-select v-model="versionNum" :popper-append-to-body="true" size="small" popper-class="history-select" @change="changeHistory">
            <el-option
              v-for="item in historyResourceList"
              :key="item.id"
              :value="item.versionNum"
              :label="handelResourceName(item)"/>
          </el-select>
        </div>
        <div class="flex-item"/>
        <ListHeader v-if="!showMobilePage" />
      </div>
      <div v-loading="loading" v-if="flag" :class="{'is-mobile':showMobilePage}" class="detail-resource create-page-container">
        <!-- 各种模块 -->
        <modules ref="modules" :style="{maxWidth: isNavOpen ? 'calc(100% - 140px)' : '100%'}" :detail-info="handleInfo" :dept-full-names="deptFullNames" :is-new-version="isNewVersion" class="modules" @changeNav="changeNav" @freshData="getResourceInfo(true)"/>
        <!-- 导航 -->
        <div :style="{width: isNavOpen ? '140px' : '0px'}" class="nav-wrap">
          <div :style="{padding: isNavOpen ? '12px 0' : '0'}" class="nav-list">
            <div v-for="item in navList" v-show="isNavOpen && showModule(item.moduleKey)" :key="item.id" :class="currentNav === item.id && 'active'" class="item" @click="changeNav(item, true)">
              <Ellipsis :content="item.name" placement="left" />
            </div>
            <div v-if="isNavOpen" class="close-btn btn" @click="switchShow">
              <img :src="closeIcon">
            </div>
            <div v-else class="open-btn btn" @click="switchShow">
              <img :src="openIcon">
            </div>
          </div>
        </div>
      </div>
      <fixed-pagination>
        <div class="center">
          <el-button v-if="info.isEditAuth && isNewVersion" class="edit-btn mobile-btn-flex" type="primary" size="small" @click="toEdit">
            编辑
          </el-button>
          <el-button v-if="showSignBtn && isNewVersion" class="Ok mobile-btn-flex" type="primary" size="small" @click="toSign">
            发起签约
          </el-button>
          <el-button v-if="showJournalBtn && isNewVersion" class="Ok mobile-btn-flex" type="primary" size="small" @click="toJournal">
            发起上刊
          </el-button>
          <el-button v-if="showCancelContract && isNewVersion" class="mobile-btn-flex" type="danger" size="small" @click="cancelContract">
            解约
          </el-button>
          <el-button
            class="back-btn cancel-btn-style"
            type="info"
            size="small"
            @click="handleBack"
          >返回</el-button>
        </div>
      </fixed-pagination>
    </template>
    <DeniedPlaceholder v-else class="no-permission"/>
  </div>
</template>
<script>
import ListHeader from '@/components/Common/header/listHeader';
import Title from '@/components/Title';
import Ellipsis from '@/components/Common/baseComponent/Ellipsis/index.vue';
import modules from './model/modules';
import { format } from '@/filters/date';
import { getResouceInfo, getResourceEditAuth } from '@/api/resource';
import { getDepartmentAll } from '@/api/config';
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import { SIGN_STATUS } from '@/utils/const/resouce';
import { commonRequiredFieldPath } from '@/utils/signUpMappingResource';
import { isJournalPlatform } from '@/views/resource/create/resourceData';
import openIcon from '@/assets/medium/openIcon.png';
import closeIcon from '@/assets/medium/closeIcon.png';

export default {
  components: {
    Title,
    ListHeader,
    modules, Ellipsis
  },
  data() {
    return {
      initDefaultData: {},
      permissionDenied: false, // 详情页是否可查看
      flag: true,
      isNavOpen: !this.showMobilePage,
      closeIcon,
      openIcon,
      hasRouteAuth,
      info: {
        autoPick: false,
        additionalKey: { // 详见rap文档
          articlesPrice: {},
          costPrice: {
            starMapTwenty: {}, // 【抖音】星图报价1-20s
            starMapSixty: {}, // 【抖音】星图报价20-60s
            starMapAboveSixty: {}, // 【抖音】星图报价60s以上
            contentCollectionPrice: {}, // 【抖音】内容合集单坑位报价
            customVideo: {}, // 【B站】定制视频
            implantationVideo: {}, // 【B站】植入视频
            publishTrends: {}, // 【B站】直发动态
            forwardTrends: {}, // 【B站】转发动态
            publish: {}, // 【微博】非原创直发
            forward: {}, // 【微博】非原创转发
            originalContent: {}, // 【微博】原创图文发布
            originalVideo: {} // 【微博】原创视频发布
          },
          monthReportPrice: {}, // 本月报备价(即本月平台价格)
          nextMonthReportPrice: {}, // 次月报备价(即次月平台价格)
          monthNotReportPrice: {}, // 本月非报备价
          nextMonthNotReportPrice: {}, // 次月非报备价
          monthReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          monthNotReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          nextMonthReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          nextMonthNotReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          microTaskCost: {
            publish: {},
            forward: {}
          },
          cooperationOption: '',
          followContractBroker: [],
          journalNode: '',
          isFrameOut: '',
          isVoiceAnchor: '',
          masterFit: '',
          orderRequest: '',
          recommendRank: '',
          freeAuth: {
            isConfirm: true,
            cost: ''
          },
          otherFreePlatform: {
            isConfirm: true,
            cost: ''
          },
          hasShopPrice: {
            isConfirm: true,
            cost: ''
          },
          addBrand: {
            isConfirm: true,
            cost: ''
          },
          retentionAllowed: {
            isConfirm: true,
            timeLimit: ''
          },
          allowCar: {
            isConfirm: true,
            cost: ''
          },
          carCommission: {
            isConfirm: true,
            cost: ''
          }
        },
        moreAccountInfo: {
          fansNum: null
        },
        morePriceInfo: {
          priceTime: {}
        },
        journalKey: {},
        moreJournalKey: {},
        costInfoKey: {},
        handoverKey: {},
        otherInfo: {}
      },
      resourceId: '', // 对应最新版的id
      historyResourceList: [],
      currentVersionId: '',
      versionNum: '', // 当前版本序号
      loading: false,
      deptTreeList: [],
      nodePathArray: [],
      deptFullNames: [], // 协作部门完整路径
      navList: [
        { name: '平台信息', id: 'platformInfo' },
        { name: '资源信息', id: 'resourceInfo' },
        { name: '创建信息', id: 'createInfo' },
        { name: '更多账号信息', id: 'moreAccountInfo' },
        { name: '上刊状态', id: 'journalStatus' },
        { name: '上刊价格', id: 'journalInfo', moduleKey: 'journal' },
        { name: '成本信息', id: 'costInfo', moduleKey: 'cost' },
        { name: '更多价格信息', id: 'morePriceInfo' },
        { name: '更多上刊信息', id: 'moreJournalInfo', moduleKey: 'moreJournalInfo' },
        { name: '签约信息', id: 'signInfo' },
        { name: '当前签约状态', id: 'statusManage' },
        { name: '更多运营信息', id: 'otherInfo' }
      ],
      currentNav: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isNewVersion() {
      if (!this.historyResourceList || !this.historyResourceList.length) return false;
      return this.versionNum === this.historyResourceList[0]['versionNum'];
    },
    showCancelContract() {
      return this.hasRouteAuth('crm:termination:create') && this.info.signStatus === 1;
    },
    kuaiShou() {
      return this.info.platformTypeName === '快手';
    },
    isCommon() {
      const arr = ['小红书', '抖音', '微博', 'B站'];
      return !arr.includes(this.info.platformTypeName);
    },
    showSignBtn() {
      return [SIGN_STATUS.NOT_SIGN, SIGN_STATUS.CANCEL].includes(this.info.signStatus) && hasRouteAuth('signUp:signUp:creat');
    },
    // 仅合作方式为“商务独家”或“经纪独家”的账号，且签约状态为已签约（自动续约）、已签约（已续约）、已签约（已签合同）且上刊状态为：下刊、已签约-不上刊
    showJournalBtn() {
      const { cooperationOption, journalStatus } = this.info.additionalKey;
      return this.isJournalPlatform && [1, 3].includes(cooperationOption) && [2, 3].includes(journalStatus) && [2, 5, 6].includes(this.info.moreAccountInfo.signDetailStatus) && hasRouteAuth('crm:upOline:create');
    },
    handleInfo() {
      return _.cloneDeep(this.info);
    },
    isJournalPlatform() {
      return isJournalPlatform(this.info.platformTypeName);
    }
  },
  created() {
    this.resourceId = Number(this.$route.params.resourceId) || '';
    this.versionNum = Number(this.$route.params.versionNum) || '';
    this.queryDeptTreeList();
    if (this.navList.length) {
      this.currentNav = this.navList[0].id;
    }
    this.initDefaultData = _.cloneDeep(this.info);
  },
  mounted() {
    window.onresize = () => {
      this.flag = false;
      this.$nextTick(() => {
        this.flag = true;
      });
    };
  },
  destroyed() {
    window.onresize = null;
  },
  methods: {
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
        this.getResourceInfo();// 确保获取部门数据
      }).catch(e => {
        console.log(e);
      });
    },
    getFullDeptName(tree, targetId) {
      for (let index = 0; index < tree.length; index++) {
        if (tree[index].children) {
          const endRecursiveLoop = this.getFullDeptName(tree[index].children, targetId);
          if (endRecursiveLoop) {
            this.nodePathArray.push(tree[index].name);
            return this.nodePathArray;
          }
        }
        if (tree[index].id === targetId) {
          this.nodePathArray.push(tree[index].name);
          return this.nodePathArray;
        }
      }
    },
    getResourceInfo(moduleEdit = false) {
      this.loading = true;
      const params = {};
      if (this.versionNum && !this.isNewVersion && !moduleEdit) {
        params.versionNum = this.versionNum;
      }
      getResouceInfo(this.resourceId, params).then(res => {
        this.loading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.deptFullNames = [];// 清空上个版本的协作部门
        if (res.data.cooperationDepartment && res.data.cooperationDepartment.length > 0) {
          res.data.cooperationDepartmentNames = res.data.cooperationDepartment.map(j => j.value).join('、');
          res.data.cooperationDepartment.forEach(el => {
            const nameArr = this.getFullDeptName(this.deptTreeList, el.id) || [];
            this.deptFullNames.push(nameArr.reverse().join('/'));
            this.nodePathArray = [];
          });
        }
        this.historyResourceList = res.data.historyResourceList || [];
        if (!this.versionNum || moduleEdit) {
          this.versionNum = res.data.historyResourceList[0]['versionNum'];
        }
        this.info = this.handleSignData(_.cloneDeep(res.data));
        getResourceEditAuth({ ids: [this.resourceId] }).then(authRes => {
          if (authRes.code === 200 && authRes.data) {
            this.$set(this.info, 'isEditAuth', authRes.data[this.resourceId]);
          }
        });
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.loading = false;
        console.log(err);
      });
    },
    handleSignData(formData) {
      const additionalKeys = Object.keys(this.initDefaultData.additionalKey);
      additionalKeys.forEach(key => {
        const outValue = formData.additionalKey[key];
        if (!outValue && outValue !== 0 && outValue !== false) {
          this.$set(formData.additionalKey, key, this.initDefaultData.additionalKey[key]);
        }
        if (Object.prototype.toString.call(formData.additionalKey[key]) === '[object Object]') {
          const innerKeys = Object.keys(formData.additionalKey[key]);
          innerKeys.forEach(innerKey => {
            const value = formData.additionalKey[key][innerKey];
            if (!value && value !== 0 && value !== false) {
              this.$set(formData.additionalKey[key], innerKey, this.initDefaultData.additionalKey[key][innerKey]);
            }
          });
        }
      });
      if (!formData.moreAccountInfo) {
        formData.moreAccountInfo = {
          fansNum: null
        };
      }
      if (!formData.morePriceInfo) {
        formData.morePriceInfo = {
          priceTime: {}
        };
      } else {
        !formData.morePriceInfo.priceTime && (formData.morePriceInfo.priceTime = {});
      }
      if (!formData.otherInfo) {
        formData.otherInfo = {
        };
      }
      const { cooperationStart, cooperationEnd, signStartDate, signEndDate } = formData.additionalKey || {};

      formData.additionalKey.signDate = signStartDate ? [signStartDate, signEndDate] : [];
      formData.additionalKey.cooperationTime = cooperationStart ? [cooperationStart, cooperationEnd] : [];
      const keys = ['journalKey', 'moreJournalKey', 'costInfoKey', 'handoverKey'];
      keys.forEach(key => {
        if (!formData[key]) {
          formData[key] = {
            dynamicKey: []
          };
        } else {
          if (!formData[key].dynamicKey)formData[key].dynamicKey = [];
        }
      });
      return formData;
    },
    // 除['微博', '抖音', '小红书', '微信']外的平台不可选择
    isPlatformFit() {
      const platformArr = ['微博', '抖音', '小红书', '微信'];
      const platformTypeName = this.info.platformTypeName;
      return platformArr.includes(platformTypeName);
    },
    handelResourceName(item) {
      const str = `v${item.versionNum}-${format(item.createTime, 'YYYY/MM/DD HH:mm')}-${item.createName}`;
      return item.versionNum === this.historyResourceList[0]['versionNum'] ? `${str}(当前)` : str;
    },
    changeHistory(versionNum) {
      this.versionNum = versionNum;
      this.getResourceInfo();
    },
    toEdit() {
      this.$router.push({
        name: 'editResource',
        params: { resourceId: this.resourceId }
      });
    },
    cancelContract() {
      const routeUrl = this.$router.resolve({
        name: 'terminationCreate',
        query: {
          mediumId: this.resourceId
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    toSign() {
      const routeUrl = this.$router.resolve({
        name: 'signUpCreate',
        query: {
          mediumId: this.resourceId,
          fromResource: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    toJournal() {
      const requiredFieldPaths = commonRequiredFieldPath.filter(el => !el.platform || el.platform.includes(this.info.platformTypeName));
      let valid = true;
      // 验证是否填写
      requiredFieldPaths.forEach(item => {
        const value = _.get(this.info, item.path);
        if ((!value && ![0, false].includes(value)) || (Array.isArray(value) && !value.length)) {
          valid = false;
        }
      });
      if (!valid) {
        this.$message.error('上刊所需信息未填写完整，请补充完整后再发起上刊');
        this.toEdit();
        return;
      }
      const routeUrl = this.$router.resolve({
        name: 'upOnlineCreate',
        query: {
          resourceId: this.resourceId,
          fromResource: 1,
          platformName: this.info.platformTypeName
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    handleBack() {
      this.$router.push({
        name: 'resource'
      });
    },
    changeNav(item, isClick = false) {
      if (isClick) {
        this.$refs.modules.scrollView(item.id);
      }
      this.currentNav = item.id;
    },
    switchShow() {
      this.isNavOpen = !this.isNavOpen;
      this.flag = false;
      this.$nextTick(() => {
        this.flag = true;
      });
    },
    showModule(key) {
      if (!key) return true;
      switch (key) {
        case 'journal':return this.kuaiShou || !this.isCommon || (this.info.journalKey.dynamicKey && this.info.journalKey.dynamicKey.length);
        case 'cost': return !this.isCommon || (this.info.costInfoKey.dynamicKey && this.info.costInfoKey.dynamicKey.length);
        case 'moreJournalInfo': return this.info.moreJournalKey.dynamicKey && this.info.moreJournalKey.dynamicKey.length;
      }
    }
  }
};
</script>
<style  lang="scss" scoped>
.detail-resource-wrap {
  min-width: 1100px;
}
.no-permission {
  min-height: calc(100vh - 60px);
  margin: 16px !important;
}
.detail-resource{
  display: flex;
  flex-wrap: nowrap;
  min-height: calc(100vh - 60px);
  position: relative;
  padding: 0 0 50px 0;
  .nav-wrap {
    width: 140px;
    transition: width .25s ease;
    flex-shrink: 0;
    .btn {
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #406EFF;
      border-radius: 4px 0 0 4px;
      cursor: pointer;
      img {
        width: 6px;
        height: 5px;
      }
    }
    .open-btn {
      top: 24px;
      left: -10px;
      width: 10px;
      height: 40px;
      color: #fff;
    }
    .close-btn {
      top: 24px;
      left: -10px;
      width: 10px;
      height: 40px;
    }
    .nav-list {
      position: fixed;
      top: 80px;
      right: 16px;
      z-index: 21;
      background-color: #fff;
      border-radius: 8px 0px 0px 8px;
      box-shadow: 0px 0px 6px 0px #dddddd;
      .item {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 116px;
        height: 28px;
        padding: 0 12px;
        margin: 0 12px;
        font-family: PingFangSC-Regular;
        color: #666666;
      }
      .item:hover, .item.active {
        background: #EDEEF2;
        border-radius: 2px;
        cursor: pointer;
      }
      .item.active {
        font-weight: bold;
        color: #406EFF;
      }
    }
  }

  &.is-mobile {
    margin: 0;
    padding-left: 12px;
    padding-right: 12px;
    ::v-deep {
      .contract-icon {
        width: 70px !important;
        right: 24px;
      }
    }
  }
  &::v-deep {
    .resource-edit-btn {
      margin-left: 12px;
    }
    .el-form-item__label{
      color: #999999;
    }
    .el-form-item__content {
      color: #333;
    }
    .el-form-item{
      margin-bottom: 0 !important;
    }
    .dividing{
      .el-col {
        .el-form-item__content {
          border-right: 1px solid #EBEEFD;
        }
        &:nth-child(3n) {
          .el-form-item__content {
            border-right: none;
          }
        }
        &:last-child {
          .el-form-item__content {
            border-right: none;
          }
        }
      }
    }
  }
}
.edit-btn {
  background-color: #fff;
  color: #406EFF;
}
.detail-top-container {
    display: flex;
    align-items: center;
    width: 100%;
    background-color: #fff;
    padding-right: 16px;
    padding-left: 16px;
    height: 48px;
    .title {
        font-size: 16px;
        line-height: 1.5;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #333333;
    }
    .flex-item {
        flex:1;
    }
    .history-resource-list {
        display: flex;
        align-items: center;
        margin-left: 39px;
        .name {
          color: #666666;
          font-size: 14px;
          font-family: PingFangSC-Regular;
          line-height: 14px;
          margin-right: 20px;
          white-space: nowrap;
        }
        &.is-mobile {
          margin-left: 0;
          &::v-deep {
            .el-select {
              width: 220px;
            }
          }
        }
        &::v-deep {
          .el-select  {
            width: 280px;
            .el-select__caret {
            color: #333;
            }
        }
      }
    }
}
</style>
<style lang="scss">
  .history-select{
    .el-select-dropdown__item{
      max-width: 100% !important;
    }
  }
</style>
